package net.mysoft.framework.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.GenericApplicationContext;

public class SpringBeanUtil implements ApplicationContextAware{
	private static GenericApplicationContext context;
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		context = (GenericApplicationContext)applicationContext;
	}
	
	public static <T> T getBean(String beanName){
		init();
		return(T)context.getBean(beanName);
	}
	
	private static void init(){
		if(null == context){
			context = new GenericApplicationContext();
			XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(context);
			xmlReader.loadBeanDefinitions("classpath*:applicationContext*.xml");
			context.refresh();
			context.registerShutdownHook();
		}
	}
}
